package com.laolang.shop.modules.member.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laolang.shop.common.core.util.AssertUtil;
import com.laolang.shop.common.core.util.SpringUtils;
import com.laolang.shop.modules.member.entity.Member;
import com.laolang.shop.modules.member.mapper.MemberMapper;
import com.laolang.shop.modules.member.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author khlbat
 * @version 1.0
 * @date 2020/11/1 20:46
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public boolean save(Member entity) {
        entity.setCreateTime(LocalDateTime.now());
        entity.setVersion(1);
        return super.save(entity);
    }

    @Override
    public Member createMember(Long userId, Long tenantId) {
        MemberService self = getSelf();

        Member insert = new Member();
        insert.setUserId(userId);
        insert.setTenantId(tenantId);
        insert.setGrade(0);
        insert.setGradeValue(0);
        insert.setIntegral(0);

        self.save(insert);
        Member entity = self.getByUserId(userId);
        AssertUtil.notNull(entity, "添加会员账号失败");
        return entity;
    }

    @Override
    public Member getByUserId(Long userId) {
        return getOne(Wrappers.<Member>lambdaQuery().eq(Member::getUserId, userId));
    }

    public MemberService getSelf() {
        return SpringUtils.getBean(MemberService.class);
    }
}
